package com.mlx.mylogin.base;

import com.mlx.mylogin.inter.LoginManager;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class LoginUtil {

    private static final MessageDigest HASH_OBJECT;

    private static LoginManager loginManager = null;

    static {
        try {
            HASH_OBJECT = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("");
        }
    }

    public static String hash256(String plaintext){
        return encryptBytes(HASH_OBJECT.digest(plaintext.getBytes(StandardCharsets.UTF_8)));
    }

    /**
     * 加密二进制数组
     * @param sBytes 二进制数组
     * @return 密文（二进制数组的16进制字符串）
     */
    private static String encryptBytes(byte[] sBytes){
        StringBuilder builder = new StringBuilder();
        String temp;
        for (byte b : sBytes){
            temp = Integer.toHexString(b & 0x000000ff);
            if (temp.length() == 1){
                temp = "0" + temp;
            }
            builder.append(temp);
        }
        return builder.toString().toUpperCase();
    }

    public static void setLoginManager(LoginManager loginManager) {
        LoginUtil.loginManager = loginManager;
    }

    /**
     * 获取Http请求对象
     */
    public static HttpServletRequest getRequest(){
        return loginManager.getRequest();
    }

    /**
     * 获取Http响应对象
     */
    public static HttpServletResponse getResponse(){
        return loginManager.getResponse();
    }


    public static HttpSession getSession(){
        return loginManager.getSession();
    }

    /**
     * http请求路径
     */
    public static String getServletPath(){
        return loginManager.getServletPath();
    }

    /**
     * 获取用户
     *
     */
    public static Object getUser(){
        return loginManager.getUser();
    }

    public static String issueToken(Object user){
        return loginManager.issueToken(user);
    }

    public static void removeToken(){
        loginManager.removeToken();
    }
}
